import MComponent from '../../common/MComponent'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import { store } from '../../store/index'
import { _score as _list } from '../../api/usercenter'
import { formatDate } from '../../utils/util'
import { testUrl } from '../../api/urls'
const app = getApp()
MComponent({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store,
    fields: {
      city: store => store.city
    }
  },
  data: {
    loading: false,
    list: {},
    total: 0,
    finished: true,
    tabs:[],
    toView:'',
    fixed:false
  },
  computed: {
    listLength() {
      let list = 0
      for(var i in this.data.list){
        if(Array.isArray(this.data.list[i])){
          list += this.data.list[i].length
        }
      }
      return list
    }
  },
  methods: {
    init() {
      this.initQuery()
    },
    initQuery() {
      const { city } = this.data
      const UnionID = wx.getStorageSync('uid')
      this.set({
        loading: true
      })
      const CityID = city ? city.ID?city.ID:0 : 0
      _list({ UnionID, CityID })
        .then(res => {
          wx.hideLoading()
          wx.stopPullDownRefresh()
          let list = res.data.data ? res.data.data : {}
          const total = res.data.data.TotalPoint
          let project = list.Project?list.Project.map(item => {
            item.tags = item.TagList ? JSON.parse(item.TagList) : []
            return item
          }):[]
          let huXing = list.HuXing?list.HuXing.map(item => {
            item.Img = item.ImgList ? JSON.parse(item.ImgList) : []
            return item
          }):[]
          let news = list.News?list.News.map(item => {
            item.addtime = formatDate(new Date(item.addtime), 'yyyy-MM-dd')
            return item
          }):[]
          let activity = list.Activity?list.Activity.map(item => {
            item.SignStartTime = formatDate(new Date(item.SignStartTime), 'yyyy-MM-dd')
            return item
          }):[]
          this.set({
            loading: false,
            list,
            project,
            huXing,
            news,
            activity,
            total,
            tabs:[
              {
                text:'推荐项目',
                value:'project',
                index:project.length
              },
              {
                text:'推荐户型',
                value:'huXing',
                index:huXing.length
              },
              {
                text:'推荐新闻',
                value:'news',
                index:news.length
              },
              {
                text:'推荐活动',
                value:'activity',
                index:activity.length
              }
            ]
          })
        })
        .catch(err => {
          console.log(err)
          wx.hideLoading()
          wx.stopPullDownRefresh()
          this.set({
            loading: false
          })
          wx.showModal({
            title: '对不起',
            content: JSON.stringify(err),
            showCancel: false
          })
        })
    },
    onChange(e){
      this.set({
        toView: this.data.tabs[e.detail.value].value
      })
    },
    // 滚动时触发
    scroll(e) {
      // console.log(e.detail.scrollTop)
      const { fixed } = this.data
      let scrollTop = e.detail.scrollTop
      let {topHeight} = this.data
      if(scrollTop>topHeight){
        this.data.fixed = true
      }else{
        this.data.fixed = false
      }
      // 避免频繁调用setData，只在关键变量发生变化后调用
      if (fixed !== this.data.fixed) {
        this.set({
          fixed: this.data.fixed,
          topshow: this.data.fixed
        })
      }
    },
    gaodu(){
      wx.createSelectorQuery().select('#top').boundingClientRect(rect1 => {
        // console.log(rect1.height)
        this.set({
          topHeight: rect1.height
        })
      }).exec()
    },
    onInit(){
      console.log(this.data.city)
      this.initQuery()
    },
    onLoad() {
      // this.init()
      console.log(this.data.city)
    },
    onShow() {
      app.loading('加载中')
      app.checkAuth()
        .then(res => {
          const uid = res
          return app.getUserInfoByUid(uid, true)
        })
        .then(memberInfo => {
          wx.hideLoading()
          this.initQuery()
        })
        .catch(err => {
          wx.hideLoading()
          console.log(err)
          wx.showModal({
            title: '温馨提示',
            content: '使用本功能前，请先登录',
            showCancel: false,
            success: r => {
              if (r.confirm) {
                wx.switchTab({
                  url: '/pages/usercenter/index'
                })
              }
            }
          })
        })
      this.gaodu();
    },
    // 事件覆盖
    xshare(){},
    onShareAppMessage(e) {
      // const { id } = this.data
      console.log(e)
      const index = e.target?e.target.dataset.index:''
      const type = e.target?e.target.dataset.type:''
      const member = wx.getStorageSync('member')
      let path = '/pages/index/index'
      let title = '欢迎您！'
      let imageUrl = ''
      switch(type) {
        case 'project':
          console.log(0)
          path = member ? `/pages/projects/detail?id=${this.data.project[index].ID}&shareunionid=${member.UnionID}` : `/pages/projects/detail`
          title = this.data.project[index].ProjectName
          imageUrl = this.data.project[index].Titleimg
          break;
        case 'huXing':
          console.log(1)
          path = member ? `/pages/projects/housetype-detail?id=${this.data.huXing[index].ID}&shareunionid=${member.UnionID}` : `/pages/projects/housetype-detail`
          title = this.data.huXing[index].ProjectName
          imageUrl = this.data.huXing[index].Img[0]
          break;
        case 'news':
          console.log(2)
          path = member ? `/pages/news/detail?id=${this.data.news[index].ID}&shareunionid=${member.UnionID}` : `/pages/news/detail`
          title = this.data.news[index].Title
          imageUrl = this.data.news[index].Img
          break;
        case 'activity':
          console.log(3)
          path = member ? `/pages/activity/detail?id=${this.data.activity[index].ID}&shareunionid=${member.UnionID}` : `/pages/activity/detail`
          title = this.data.activity[index].Title
          imageUrl = this.data.activity[index].Img
          break;
        default:
          console.log(4)
      } 
      return {
        path: path,
        title: title,
        imageUrl
      }
    }
  }
})
